//https://leetcode.cn/problems/pacific-atlantic-water-flow/

class Solution {
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int m, n;
public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights)
    {
        m = heights.size();
        n = heights[0].size();

        vector<vector<bool>> pac(m, vector<bool>(n));
        vector<vector<bool>> atl(m, vector<bool>(n));

        for (int j = 0; j < n; j++) dfs(heights, 0, j, pac);
        for (int i = 0; i < m; i++) dfs(heights, i, 0, pac);
        for (int j = 0; j < n; j++) dfs(heights, m - 1, j, atl);
        for (int i = 0; i < m; i++) dfs(heights, i, n - 1, atl);

        vector<vector<int>> ret;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (pac[i][j] && atl[i][j])
                {
                    ret.push_back({ i,j });
                }
            }
        }

        return ret;

    }

    void dfs(vector<vector<int>>& heights, int i, int j, vector<vector<bool>>& vist)
    {
        vist[i][j] = true;

        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k];
            int y = j + dy[k];

            if (x >= 0 && x < m && y >= 0 && y < n && !vist[x][y] && heights[x][y] >= heights[i][j])
                dfs(heights, x, y, vist);
        }
    }
};